<template>
  <div>
    <el-upload
      :before-upload="beforeUpload"
      :on-change="onChange"
      :http-request="httpRequest"
      :on-remove="onRemove"
      :class="{disabled:fileList.length>0}"
      class="upload"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="onPreview"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible="isshowDialog" @close="isshowDialog=false">
      <img width="100%" :src="dialogImg" alt="">
    </el-dialog>
    <el-progress v-if="progressDefault" class="progress" :text-inside="true" :stroke-width="26" :percentage="progressImg" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDIQHrCG4cvxhAMIxLSJtCEzUjhOp0uYw3',
  SecretKey: 'rRloa5IFvLVP2OTIp79uObXCbjcGelbB'
})
export default {

  data() {
    return {
      progressDefault: false,
      progressImg: 0,
      dialogImg: '',
      isshowDialog: false,
      fileList: []
    }
  },
  methods: {
    onPreview(file) {
      this.isshowDialog = true
      this.dialogImg = file.url
    },
    onRemove(file, newfileList) {
      this.fileList = newfileList
    },
    httpRequest(params) {
      this.progressDefault = true
      cos.putObject({
        Bucket: 'hr67-1307767593', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          this.progressImg = progressData.percent * 100
          setTimeout(() => {
            this.progressDefault = false
          }, 1000)
        }
      }, function(err, data) {
        console.log(err || data)
      })
    },
    onChange(file, newfileList) {
      this.fileList = newfileList
    },
    beforeUpload(file) {
      // 控制上传的大小
      const maxSize = 2 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('最多只能上传2M以下的图片')
        return false
      }
      // 控制上传图片的类型
      const allowedType = ['image/jpeg', 'image/png']
      if (allowedType.indexOf(file.type) === -1) {
        this.$message.warning('只支持 jpeg / png 类型图片 ')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled{
::v-deep .el-upload--picture-card{
  display: none;
}
}
.progress{
width: 148px;
}
</style>
